/**
 * <br>项目名: ThreadTest
 * <br>文件名: ExchangerTest.java
 * <br>Copyright 2018   国信嘉宁数据技术有限公司
 */
package src;

import java.util.Random;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/** 
 * <br>类 名: ExchangerTest 
 * <br>描 述: 描述类完成的主要功能 
 * <br>作 者: zhaowei 
 * <br>创 建: 2018年6月5日 
 * <br>版 本: v1.0.0 
 * <br>
 * <br>历 史: (版本) 作者 时间 注释
 */
public class ExchangerTest {

	/**
	 * <br>描 述:
	 * <br>作 者: zhaowei 
	 * <br>历 史: (版本) 作者 时间 注释
	 * @param args
	 */
	public static void main(String[] args) {
		Exchanger<Integer> exchanger = new Exchanger<Integer>();   
        new Girl(exchanger).start();    
        new Man(exchanger).start();    
	}
}

/** 
 * 男人 
 * @author admin 
 */  
class Man extends Thread {    
    Exchanger<Integer> exchanger = null;    
    public Man(Exchanger<Integer> exchanger) {    
        super();    
        this.exchanger = exchanger;    
    }    
    @Override    
    public void run() {    
        Random rand = new Random();  
        int money = 0;  
        for(int i=0;i<8;i++){  
            money+=rand.nextInt(100000);//年薪在10万以内  
            try {  
            	Thread.sleep(1000);
                exchanger.exchange(money,1000,TimeUnit.MILLISECONDS);//存钱  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            } catch (TimeoutException e) {
				e.printStackTrace();
			}  
        }  
    }    
} 

/** 
 * 女人 
 */  
class Girl extends Thread {
	Exchanger<Integer> exchanger = null;
	int money = 0;

	public Girl(Exchanger<Integer> exchanger) {
		super();
		this.exchanger = exchanger;
	}

	@Override
	public void run() {
		for (int i = 0; i < 8; i++) {
			try {
				Thread.sleep(1000);
				money = exchanger.exchange(money,1000,TimeUnit.MILLISECONDS);
				System.out.println(money > 300000 ? "亲爱的" + money + "万我们可以结婚了" : money + "块这么少," + "臭屌丝活该单身,还不去赚钱娶老婆");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (TimeoutException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
